-module(mochiweb_simple_get).

-include_lib("../include/ewgi_unit.hrl").
-include("../../include/ewgi.hrl").

-export([loop/1, handle_req/2]).

-define(PORT, 8000).

-define(DEFAULTS, [{name, ?MODULE},
                   {port, ?PORT}]).

-define(RESPONSE, <<"It's working!">>).
-define(CONTENT_TYPE, "application/x-www-form-urlencoded").
-define(DATA, "foo=bar&bar=baz").

%%--------------------
%% Tests
%%--------------------
%% Setup Tests
setup_test() ->
    try
        application:start(inets),
        {ok, _Pid} = mochiweb_http:start([{loop, fun ?MODULE:loop/1} | ?DEFAULTS])
    catch
	Err:Reason ->
            error_logger:error_report({Err, Reason}),
	    error
    end.

loop(Req) ->
    M = ewgi_mochiweb:new(fun ?MODULE:handle_req/2),
    M:run(Req).

handle_req(Env, StartResp) ->
    ?eq(ewgi_api:server_sw(Env), "MochiWeb"),
    ?eq(ewgi_api:server_name(Env), "localhost"),
    ?eq(ewgi_api:gw_interface(Env),"EWGI/1.0"),
    ?eq(ewgi_api:server_protocol(Env), "HTTP/1.1"),
    ?eq(ewgi_api:server_port(Env), 8000),
    ?eq(ewgi_api:method(Env), 'GET'),
    ?eq(ewgi_api:path_info(Env), "/"),
    ?eq(ewgi_api:path_translated(Env), undefined),
    ?eq(ewgi_api:script_name(Env), ""),
    % same hanlder for 2 GET requests.
    % one has a query string and one hasn't
    % check for both
    Qs = ewgi_api:qs(Env),
    ?true((Qs=="") or (Qs==?DATA)),
    ?eq(ewgi_api:content_type(Env), undefined),
    ?eq(ewgi_api:content_length(Env), undefined),
    Headers = [{"HTTP_CONNECTION", "keep-alive"}, {"HTTP_HOST", "localhost"}, {"HTTP_TE", []}],
    ?eq(ewgi_api:get_all_headers(Env), Headers),
    ?eq(ewgi_api:remote_host(Env), undefined),
    ?eq(ewgi_api:remote_addr(Env), "127.0.0.1"),
    ?eq(ewgi_api:auth_type(Env), undefined),
    ?eq(ewgi_api:remote_user(Env), undefined),
    ?eq(ewgi_api:remote_ident(Env),undefined),
    ?eq(ewgi_api:url_scheme(Env), "http"),
    ?eq(ewgi_api:version(Env), {1, 0}),
    ?eq(ewgi_api:get_all_data(Env), []),
    StartResp(?OK, []),
    ?RESPONSE.

test_simple_req() ->
    {ok, Result} = http:request("http://localhost:8000/"),
    {Proto, _Headers, Body} = Result,
    [?eq(Proto, {"HTTP/1.1", 200, "OK"}),
     ?eq(Body, binary_to_list(?RESPONSE))].

test_simple_with_qs() ->
    {ok, Result} = http:request("http://localhost:8000/?foo=bar&bar=baz"),
    {Proto, _Headers, Body} = Result,
    [?eq(Proto, {"HTTP/1.1", 200, "OK"}),
     ?eq(Body, binary_to_list(?RESPONSE))].

%%--------------------
%% Internal Functions
%%--------------------

end_test() ->
    mochiweb_http:stop(?MODULE).

